﻿using System.Data;
using System.Text;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace DataTablesInteractions
{
    public class JsonDataManager
    {
        //expose the datatable publicly so it can be swapped out by the caller
        public DataTable BaseDataTable;
        public List<BusinessLogic.Table> BaseTableList;

        public JsonDataManager(DataTable BaseData)
        {
            BaseDataTable = BaseData;
        }

        public JsonDataManager(List<BusinessLogic.Table> BaseData)
        {
            BaseTableList = BaseData;
        }

        public string DataAsJson()
        {
            if (BaseDataTable == null)
            {
                return JsonConvert.SerializeObject(BaseTableList, Formatting.None);
            }
            else
            {
                //return JsonConvert.SerializeObject(BaseDataTable, Formatting.None);
                StringBuilder sb = new StringBuilder();
                int rowcount = 0;
                sb.Append("[");
                foreach (DataRow dr in BaseDataTable.Rows)
                {
                    string currrow = "[";
                    foreach (DataColumn dc in BaseDataTable.Columns)
                    {
                        if (currrow != "[") { currrow += ","; }
                        currrow += "'" + dr[dc].ToString() + "'";
                    }
                    currrow += "]";
                    if (0 < rowcount)
                    {
                        currrow = "," + currrow;
                    }
                    sb.Append(currrow);
                    ++rowcount;
                }
                sb.Append("]");
                return sb.ToString();
            }
        }

        public string SerializedTable()
        {
            if (BaseDataTable == null)
            {
                return DataAsJson();
            }
            else
            {
                return JsonConvert.SerializeObject(BaseDataTable, Formatting.None);
            }
        }

        public string ColumnHeadersAsJson()
        {
            List<DataTablesInteractions.DataTablesColumnHeader> columnHeaders = new List<DataTablesInteractions.DataTablesColumnHeader>();
            string serializedTable = SerializedTable();
            string firstrow = serializedTable.Split('}')[0].Substring(1, serializedTable.Split('}')[0].Length - 1) + "}";
            Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(firstrow);
            foreach (string s in values.Keys)
            {
                columnHeaders.Add(new DataTablesColumnHeader(s));
            }
            return JsonConvert.SerializeObject(columnHeaders);
        }
    }
}